<template>
  <el-row class="user-info-form" type="flex" justify="center">
    <el-col>
      <el-form label-position="top" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
        <el-form-item label="添加现场照片/视频：" prop="pictures">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="false"
            ref="upload"
            list-type="picture-card"
            :data="coverPicQiniuData"
            :on-success="function(res, file, fileList) {return handleAvatarSuccess(res, file, fileList, 'coverPicQiniuData')}"
            :on-error="function(res) {return handleError(res, 'coverPicQiniuData')}"
            :before-upload="function(file){return beforeAvatarUpload(file, 'coverPicQiniuData')}"
            :file-list="coverPicQiniuData.fileList"
            :limit="9"
            :on-exceed="function(files, fileList) {return handleExceed(files, fileList, 'coverPicQiniuData')}"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png, video/mp4, video/3gp, video/mpeg, video/mavip4, video/flv, video/mov"
          >
            <template v-slot:file="scope" class="videoImage">
              <div style="width:100%;height:100%;">
                <img
                  v-if="'mp4,3gp,mpeg,mavip4,mov,flv'.includes(scope.file.raw.name.split('.')[scope.file.raw.name.split('.').length - 1].toLowerCase())"
                  style="width:100%;height:100%;"
                  :src="require('@/assets/images/video/video-detail.png')"
                />
                <img v-else :src="scope.file.url" style="width:100%;height:100%;" alt="图片" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    :data-type="scope.file.raw.type"
                    :data-imgpreview="scope.file.url"
                    @click="$imgPreview"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    class="el-upload-list__item-delete"
                    @click="deleteVideo(scope.file, coverPicQiniuData.fileList, 'coverPicQiniuData')"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
                <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-check"></i>
                  <i class="el-icon-close"></i>
                  <i class="el-icon-close-tip"></i>
                </label>
              </div>
            </template>
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="隐患描述：" prop="describe">
          <el-input v-model="editForm.describe" auto-complete="off" placeholder="请输入隐患描述"></el-input>
        </el-form-item>
        <el-form-item label="所在单位：" prop="unit">
          <el-select clearable @change="getList()" v-model="editForm.unit" placeholder="请选择业主单位">
            <el-option
              v-for="item in orgList"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在建筑：" prop="build">
          <tree-select
            v-model="editForm.build"
            placeholder="请选择所在建筑"
            filterable
            :width="536"
            :data="buildList"
            :defaultProps="buildDefaultProps"
            :checkedKeys="defaultCheckedFbsId"
            :nodeKey="buildNodeKey"
            @node-click="buildNodeClick"
          ></tree-select>
        </el-form-item>
        <el-form-item label="具体位置：" prop="location">
          <el-input v-model="editForm.location" auto-complete="off" placeholder="明确的描述能够确保他人快速定位隐患位置"></el-input>
        </el-form-item>
        <el-form-item label="相关资产：" prop="property">
          <el-select
            v-model="editForm.property"
            clearable
            filterable
            :loading="assetsLoading"
            placeholder="请选择相关资产"
            remote
            :remote-method="remoteMethod"
            @clear="clearAssets"
            @change="change1()"
          >
            <el-option v-for="item in assetFcOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            <el-pagination
              :page-size="30"
              @current-change="assetsPageChange"
              :current-page.sync="assetsIndex"
              small
              layout="total, prev, pager, next"
              :total="assetsTotal"
            ></el-pagination>
          </el-select>
        </el-form-item>
        <el-form-item label="相关物联设备：" prop="equipment">
          <el-select
            v-model="editForm.equipment"
            clearable
            filterable
            :loading="equipLoading"
            placeholder="请选择物联设备"
            remote
            :remote-method="remoteMethodEquip"
            @clear="clearEquip"
            @change="change1()"
          >
            <el-option v-for="item in equipList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            <el-pagination
              :page-size="30"
              @current-change="equipPageChange"
              :current-page.sync="equipIndex"
              small
              layout="total, prev, pager, next"
              :total="equipTotal"
            ></el-pagination>
          </el-select>
        </el-form-item>
        <el-form-item label="责任指派：">
          <div @change="getRadio">
            <el-radio v-model="radio1" label="1" border>选择指派人</el-radio>
            <el-radio v-model="radio1" label="2" border>选择责任人</el-radio>
          </div>
        </el-form-item>
        <el-form-item v-if="chooseRadio" label="指派人：" prop="assignor">
          <el-select filterable @change="change1()" v-model="editForm.assignor" placeholder="请选择指派人">
            <el-option
              v-for="item in personnelOptions"
              :key="item.accountName"
              :label="item.name"
              :value="item.accountName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!chooseRadio" label="隐患等级：" prop="level">
          <el-select filterable @change="change1()" v-model="editForm.level" placeholder="请选择隐患等级">
            <el-option
              v-for="item in personnelOption"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!chooseRadio" label="隐患类别：" prop="categoryId">
          <el-select filterable v-model="editForm.categoryId" placeholder="请选择隐患类别">
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.text" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!chooseRadio" label="责任人：" prop="person">
          <el-select filterable @change="change1()" v-model="editForm.person" placeholder="请选择责任人">
            <el-option
              v-for="item in personnelOptions"
              :key="item.accountName"
              :label="item.name"
              :value="item.accountName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!chooseRadio" label="整改期限：" prop="reform">
          <el-select filterable @change="change1()" v-model="editForm.reform" placeholder="请选择整改期限">
            <el-option v-for="item in endTime" :key="item.code" :label="item.name" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!chooseRadio&&editForm.reform===0" prop="days">
          <el-input-number v-model="editForm.days" :controls="false" :min="1"></el-input-number>
          <span style="margin-left:10px;">个工作日</span>
        </el-form-item>

        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button round @click="closeDialog">取消</el-button>
          <el-button round type="primary" @click="saveForm('editForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import utils from '@/utils/util'
import { getSysFcfCategoryTree, getFcfStatusList } from '@/api/fcf'
import { saveHiddenDanger } from '@/api/communicat'
import { getPInfo, getOrgList } from '@/api/org'
import { getFbsTree } from '@/api/fbs'
import { getDictByCode } from '@/api/dic'
import { getAListForPc } from '@/api/assets'
import { getHaveOrgUserList } from '@/api/maintence'
import { qnToken } from '@/api/api'
import TreeSelect from '@/libs/TreeSelect/Main'
let TYPEMAP = {
  coverPicQiniuData: '现场图片',
}

export default {
  name: 'AddMailForm',
  components: {
    TreeSelect,
  },
  props: ['closeDialog', 'oldInfo'],
  data() {
    return {
      editForm: {
        describe: '',
        unit: '',
        location: '',
        build: '',
        property: '',
        equipment: '',
        assignor: '',
        level: '',
        classification: '',
        person: '',
        reform: '',
        pictures: '',
        days: '',
      },
      categoryOptions: [],
      radio1: '1',
      assetFcOptions: [], // 关联物联设备
      utils: utils,
      personnelOptions: [],
      endTime: [
        { name: '24小时', code: 1 },
        { name: '5个工作日', code: 2 },
        { name: '10个工作日', code: 3 },
        { name: '30个工作日', code: 4 },
        { name: '3个月内', code: 5 },
        { name: '半年内', code: 6 },
        { name: '自定义', code: 0 },
      ],
      personnelOption: [],
      // 选择指派
      chooseRadio: true,
      // 现场图片
      coverPicQiniuData: {
        key: '',
        fileList: [],
      },
      // 上传图片携带的默认参数
      qiniuDefaultData: {
        token: '',
      },
      // 物联设备
      equipList: [],
      equipIndex: 1,
      equipTotal: 0,
      equipLoading: false,
      // 建筑物
      buildList: [],
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      placeOptions: [],
      // 搜索
      searchForm: {
        orgIds: this.$store.state.userinfo.organizationIds,
        systemId: '-1',
        fcfCategoryId: '',
        fbsId: 0,
        name: '',
        fireTType: '-1',
      },
      // 富文本编辑器上传
      qiniuDataEditor: {
        key: '',
        fileList: [],
      },
      defaultCheckedFbsId: [],
      editFormRules: {
        describe: [
          { required: true, message: '请输入隐患描述', trigger: 'blur' },
        ],
        unit: [{ required: true, message: '请选择所在单位', trigger: 'blur' }],
        build: [{ required: true, message: '请选择所在建筑', trigger: 'blur' }],
        pictures: [
          { required: true, message: '请选择图片', trigger: 'change' },
        ],
        assignor: [
          { required: true, message: '请选择指派人', trigger: 'blur' },
        ],
        level: [{ required: true, message: '请选择隐患等级', trigger: 'blur' }],
        categoryId: [
          { required: true, message: '请选择隐患类别', trigger: 'blur' },
        ],
        person: [{ required: true, message: '请选择责任人', trigger: 'blur' }],
        reform: [
          { required: true, message: '请选择整改期限', trigger: 'blur' },
        ],
        days: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      orgList: [],
      assetsLoading: false,
      assetsIndex: 1,
      assetsTotal: 0,
    }
  },
  created() {
    this.$emit('show_loading', false)
    let that = this
    //上传之前获取 token
    qnToken({}).then((res) => {
      that.qiniuDefaultData.token = res.data
      $.extend(that.qiniuDataEditor, that.qiniuDefaultData)
      $.extend(that.coverPicQiniuData, that.qiniuDefaultData)
    })
    that.getOrgListData()
  },
  methods: {
    equipPageChange(val) {
      this.getEquipList(val - 1)
    },
    clearEquip() {
      this.equipQuery = ''
      this.equipIndex = 1
      this.getEquipList()
    },
    remoteMethodEquip(query) {
      this.equipQuery = query
      this.equipIndex = 1
      this.getEquipList()
    },
    clearAssets() {
      this.assetsQuery = ''
      this.assetsIndex = 1
      this.getAssetSelectList()
    },
    remoteMethod(query) {
      this.assetsQuery = query
      this.assetsIndex = 1
      this.getAssetSelectList()
    },
    assetsPageChange(val) {
      this.getAssetSelectList(val - 1)
    },
    //创建隐患
    saveForm(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let _this = this
      _this.$emit('show_loading', true)
      _this.editForm.pictures = utils.ilinkArrHandle
        .getqiniuPicUrlArr(_this.coverPicQiniuData.fileList)
        .toString()
      let parame = {}
      if (_this.radio1 == 2) {
        parame = {
          id: 0,
          orgId: _this.editForm.unit,
          fbsId: _this.editForm.build,
          relateAssetsIds: _this.editForm.property,
          relateFcfIds: _this.editForm.equipment,
          categoryId: _this.editForm.categoryId,
          gradeId: _this.editForm.level,
          chargePerson: _this.editForm.person,
          picUrls: _this.editForm.pictures,
          hiddenDangerDesc: _this.editForm.describe,
          addrDesc: _this.editForm.location,
          createAccount: _this.$store.state.userinfo.accountName,
          endTimeType: _this.editForm.reform,
          days: _this.editForm.reform === 0 ? _this.editForm.days : '',
          status: 1,
        }
      } else {
        parame = {
          id: 0,
          orgId: _this.editForm.unit,
          fbsId: _this.editForm.build,
          relateAssetsIds: _this.editForm.property,
          relateFcfIds: _this.editForm.equipment,
          categoryId: _this.editForm.categoryId,
          managerPerson: _this.editForm.assignor,
          picUrls: _this.editForm.pictures,
          hiddenDangerDesc: _this.editForm.describe,
          addrDesc: _this.editForm.location,
          createAccount: _this.$store.state.userinfo.accountName,
          status: 5,
        }
      }

      _this.$refs[formName].validate((valid) => {
        if (valid) {
          saveHiddenDanger(parame).then((res) => {
            if (res.status === 200) {
              _this.$message({
                message: '保存成功！',
                type: 'success',
              })
            } else {
              _this.$message.error(res.info)
            }
            _this.$emit('show_loading', false)
            _this.closeDialog()
          })
        } else {
          _this.$emit('show_loading', false)
          return false
        }
      })
    },
    // 获取业主单位信息
    getOrgListData() {
      let that = this
      getOrgList({
        queryType: 0,
      }).then((res) => {
        if ((res.status = 200)) {
          that.orgList = res.data
          that.getDictByCode()
          that.getCategory()
        }
      })
    },
    // 获取建筑物数据
    getBuildList() {
      let that = this
      getFbsTree({
        organizationId: that.editForm.unit,
      }).then((res) => {
        that.buildList = res.data
      })
    },
    /*资产*/
    getAssetSelectList(pageIndex = 0) {
      let self = this
      this.assetsLoading = true
      getAListForPc({
        name: this.assetsQuery || '',
        queryType: 1,
        organizationId: self.editForm.unit,
        userName: self.$store.state.userinfo.accountName,
        systemId: '-1',
        fbsIds: this.editForm.build.toString(),
        isUse: -1,
        pageSize: 30,
        pageIndex,
      }).then((data) => {
        this.assetsLoading = false
        if (data.status === 200) {
          self.assetFcOptions = data.data
          this.assetsTotal = data.total
        }
      })
    },
    buildNodeClick(item) {
      this.editForm.build = item.id
      this.getAssetSelectList()
      this.getEquipList()
    },

    // 获取物联设备
    getEquipList(pageIndex = 0) {
      let that = this
      this.equipLoading = true
      getFcfStatusList({
        name: this.equipQuery || '',
        orgIds: that.editForm.unit,
        fbsId: this.editForm.build,
        systemId: -1,
        fireTType: -1,
        pageSize: 30,
        pageIndex,
        queryType: 1,
      }).then((res) => {
        this.equipLoading = false
        that.equipList = res.data
        this.equipTotal = res.total
      })
    },

    //指派人
    getMaintenanceUser() {
      let that = this
      getHaveOrgUserList({
        orgIds: that.$store.state.userinfo.organizationIds,
      }).then((res) => {
        if (res.status === 200) {
          that.personnelOptions = res.data
        }
      })
    },
    //重选单位
    getList() {
      let _this = this
      _this.editForm.build = ''
      _this.editForm.property = ''
      _this.editForm.assignor = ''
      _this.editForm.equipment = ''
      _this.defaultCheckedFbsId = []
      _this.buildList = []
      _this.assetFcOptions = []
      this.equipList = []
      _this.getBuildList()
      _this.getMaintenanceUser()
    },
    change1() {
      this.$forceUpdate()
    },
    //获取隐患等级
    getDictByCode() {
      let _this = this
      getDictByCode({ code: 49 }).then((res) => {
        if (res.status === 200) {
          _this.personnelOption = res.data.dictValueObj
        }
      })
    },
    getCategory() {
      // 绑定隐患类型下拉框
      let _this = this
      getDictByCode({
        code: 50,
        dictKey: 1,
      }).then((res) => {
        _this.categoryOptions = JSON.parse(res.data.dictValueObj[0].dictValue)
      })
    },

    // 消防系统与设备类别树被点击
    handleNodeClick(obj, node, item) {
      let that = this
      if (obj.hasOwnProperty('parentId')) {
        // 记录系统id和设备类别id
        that.searchForm.systemId = node.parent.data.id || ''
        that.searchForm.fcfCategoryId = obj.id
      } else {
        // 记录系统id和设备类别id
        that.searchForm.systemId = obj.id
        that.searchForm.fcfCategoryId = ''
      }
      // that.search();
    },
    getRadio() {
      let _this = this
      if (_this.radio1 == 1) {
        _this.chooseRadio = true
        _this.editForm.level = ''
        _this.editForm.categoryId = ''
        _this.editForm.person = ''
        _this.editForm.reform = ''
      } else {
        _this.chooseRadio = false
        _this.editForm.assignor = ''
      }
    },
    // 重命名和校验
    beforeAvatarUpload(file, type, obj) {
      let isAgainUpload = false
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      if (obj) {
        obj[type].key = fielLocalName + '_' + new Date().getTime() + fielType
      } else {
        this[type].key = fielLocalName + '_' + new Date().getTime() + fielType
      }
      const isLt20M = file.size / 1024 / 1024 < 20

      this.coverPicQiniuData.fileList.forEach((item) => {
        if (file.name === item.name && file.size === file.size) {
          isAgainUpload = true
          return false
        }
      })

      if (isAgainUpload) {
        this.$message.error('不能上传重复的照片或视频！')
        return false
      }

      if (
        'mp4,3gp,mpeg,mavip4,mov,flv'.includes(
          file.name.split('.')[file.name.split('.').length - 1].toLowerCase()
        )
      ) {
        return this.getVideoTimeLength(file) // 最长30s
      } else if (
        'png,jpg,jpeg,bmp,gif'.includes(
          file.name.split('.')[file.name.split('.').length - 1].toLowerCase()
        )
      ) {
        if (!isLt20M) {
          this.$message.error('现场图片大小不能超过 20MB!')
          return false
        }
      } else {
        this.$message.error('上传文件格式不正确 !')
        return false
      }
    },
    // 获取视频时长
    getVideoTimeLength(file) {
      let _this = this
      let url = URL.createObjectURL(file)
      let audioElement = new Audio(url)
      let duration // 视频时长
      return new Promise((resolve, reject) => {
        audioElement.addEventListener('loadedmetadata', function (_event) {
          duration = audioElement.duration //时长为秒，小数
          if (Math.floor(duration) > 30) {
            _this.$message.error('现场视频时长不能超过30s !')
            reject()
          } else {
            resolve()
          }
        })
      })
    },
    // 删除视频
    deleteVideo(file, fileList, type, obj) {
      fileList.forEach((item, index) => {
        if (item.uid == file.uid) {
          fileList.splice(index, 1)
        }
      })
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
    },
    // 上传成功
    handleAvatarSuccess(res, file, fileList, type, obj) {
      if (obj) {
        obj[type].fileList = fileList
      } else {
        this[type].fileList = fileList
      }
    },
    handleError(res, type) {
      this.$message({
        message: `${TYPEMAP[type]}上传失败`,
        duration: 2000,
        type: 'warning',
      })
    },
    handleExceed(files, fileList, type) {
      this.$message.warning(
        `${TYPEMAP[type]}最多只能上传9张，如需重新上传请先删除原先图片`
      )
    },
  },
}
</script>

<style lang="scss">
.videoPreview {
  .videoPreview_videoDisplay {
    display: block;
    margin: 0 auto;
  }
  .container-imgpre {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
